
var modifyOrAddFlag;
//初始化数据
var ddvDatagrid = {};
	
  $(document).ready(function(){
		$('#win').window('close');
		$('#winEdit').window('close');
		
		$('#comboxCompanyName').combobox({
			editable: false,
			url: BASE_URL_COMPANY_SEARCH + '/findByExample' + '?v=' + Math.random(),
			valueField: 'id',
		    textField: 'orgName',
		    method:'get',
		    loadFilter:function(data){
		    	return data.content;
		    }
		    
		});
		//导入
		$('#import_link').window({
			width:465,
			modal:true,
			minimizable:false,
			maximizable:false,
			collapsible:false
		});
		$('#import_link').window('close');  //关闭窗口
		
		$("#selFileBtn").click(function(e){
			e.preventDefault();
			//$("#file").click();
		});
		
		$(".import_con").delegate("#importLinkFile" ,"change", function() {
		    $("#fileName").val($('#importLinkFile').val());
		    //clearAutofillStyle();
		});
		
		$(".button_con a" ).removeClass("l-btn-plain");
		$("#datagrid").datagrid({
			url : BASE_URL_COMPANY_SEARCH + '/findByExample' + '?v=' + Math.random(),
			method:'get',
			view: detailview,
			autoRowHeight:true,
			nowrap:false,
			pageSize:20,
			singleSelect:true,
			striped:true,
			 detailFormatter:function(index,row){
                 return '<div style="padding:2px"><table class="ddv"></table></div>';
             },
			pageList:[10,20,50,100],
			columns:[[
						{field:'',width:10,checkbox:true},
						{field:'orgName',title:'公司',width:100,align:'left'},
			      ]],
			pagination:true,
			onSelect:function(rowIndex,rowData){
				$("#toolbar_edit").linkbutton('enable');
				$("#toolbar_delete").linkbutton('enable');
			},
			onBeforeCheck: function(rowIndex,rowData){
				$('#datagrid').datagrid('clearChecked');
				$('#datagrid').datagrid('clearSelections');
				
				for(var i in ddvDatagrid)
				{
					ddvDatagrid[i].datagrid('clearChecked');
					ddvDatagrid[i].datagrid('clearSelections');
				}
			},
			loadFilter:function(data){
				return {
					total: data.totalElements,
					rows: data.content
				};
			},
			onExpandRow: function(index,row){
				ddvDatagrid[row.id] = $(this).datagrid('getRowDetail',index).find('table.ddv');
				ddvDatagrid[row.id].datagrid({
                    url:BASE_URL_COMPANY_SEARCH + '/findByExamples' + '?v=' + Math.random(),
                    fitColumns:true,
                    singleSelect:true,
                    rownumbers:true,
                    loadMsg:'',
                    height:'auto',
                    pageSize:20,
                    pagination:true,
                    pageList:[20,50,100],
                    columns:[[
							{field:'',width:10,checkbox:true},
							{field:'orgName',title:'部门名称',width:300},
                    ]],
                    onBeforeCheck: function(rowIndex,rowData){
        				$('#datagrid').datagrid('clearChecked');
        				$('#datagrid').datagrid('clearSelections');
        				for(var i in ddvDatagrid)
        				{
        					ddvDatagrid[i].datagrid('clearChecked');
        					ddvDatagrid[i].datagrid('clearSelections');
        				}
        			},
                    loadFilter:function(data){
        				return {
        					total: data.totalElements,
        					rows: data.content
        				};
        			},
        			onLoadSuccess: function(data) {
        				$('#datagrid').datagrid('fixDetailRowHeight',index);
        			},
        			onBeforeLoad:function(param){
        				param.page -= 1;
        				param.size = param.rows;
        				delete param.rows;
        				
        				param.sort = 'createTime,desc';
        				param.id = row.id;
        				
        			}
                });
                $('#datagrid').datagrid('fixDetailRowHeight',index);
            },
			onBeforeLoad:function(param){
				param.page -= 1;
				param.size = param.rows;
				delete param.rows;
				
				param.sort = 'createTime,desc';
				
			}
		});
		
		$("#datagrid").datagrid('getPager').pagination({   
		    displayMsg:'当前显示从 [{from}] 到 [{to}] 共[{total}]条记录'
		}); 

});
 
 	function addCom(){
 		modifyOrAddFlag = true;
 		$('#addForm')[0].reset();
 		$("#win").window('setTitle','公司管理-新增');
 		$('#win').window('open');
	}
 	
 	function addDep(){
		modifyOrAddFlag = true;
		$('#addForm2')[0].reset();
		var data = $('#comboxCompanyName').combobox('getData');
		$("#comboxCompanyName").combobox('setValue',data[0].id);
		$("#comboxCompanyName").siblings(".textbox").children(".textbox-text").val($("#comboxCompanyName").combobox('getText'));
		
		$("#winEdit").window('setTitle','公司部门管理-新增');
		$('#winEdit').window('open');
	}
 	//新增和修改
 	function save(){
 		if($("#addForm").form("validate")){
 	 		var orgName = $("#companyName").val();
 	 		var level = '1';
 	 		var newCompanyInfo = {orgName:orgName,level:level};
 	 		var checkParam = {name:orgName,level:level};
			$("#instance_save").linkbutton("disable");
			$("#instance_save .l-btn-text").text("提交中...");
	 		if(!modifyOrAddFlag){
	 	 		var row = $('#datagrid').datagrid('getSelected');
	 	 		checkParam.originalId = row.id;
	 	 		if(row.orgName == checkParam.orgName) // 未修改公司的名字，则可以直接修改
				{
	 	 			modifyCompany(newCompanyInfo);
				}
				else
				{
					$.ajax({
			    		type: "get",
			    		url: BASE_URL_COMPANY_SEARCH + '/checkIsCanSave' + '?v=' + Math.random(),
			    		data: checkParam,
			    		contentType: "application/json",
			    		success: function(result) {
			    			if(result.isCanSave == true)
		    				{
			    				modifyCompany(newCompanyInfo);
		    				}
		    				else 
	    					{
		    					if (result.errorCode == "DUPLICATE") 
								{
			    					$("#instance_save").linkbutton("enable");
			    					$("#instance_save .l-btn-text").text("保存");
									$.messager.alert('错误',"<p>修改失败，公司名称已存在！</p>","error");
								}
								else
								{
									$("#instance_save").linkbutton("enable");
									$("#instance_save .l-btn-text").text("保存");
									$.messager.alert('错误',"<p>修改失败！</p>","error");
								}
	    					}
			    		},
						error: function() {
							$("#instance_save").linkbutton("enable");
							$("#instance_save .l-btn-text").text("保存");
							$.messager.alert('错误','<p>服务异常，修改公司信息失败，请稍后重试或联系管理员!</p>', 'error');
						}
			    	});
				}
	 		}else{
	 			$.ajax({
		    		type: "get",
		    		url: BASE_URL_COMPANY_SEARCH + '/checkIsCanSave' + '?v=' + Math.random(),
		    		data: checkParam,
		    		contentType: "application/json",
		    		success: function(result) {
	    				if(result.isCanSave == true)
	    				{
	    					addCompany(newCompanyInfo);
	    				}
	    				else 
	    				{
	    					if (result.errorCode == "DUPLICATE") 
	    					{
	        					$("#instance_save").linkbutton("enable");
	        					$("#instance_save .l-btn-text").text("保存");
	    						$.messager.alert('错误',"<p>新增失败，公司名称已存在！</p>","error");
	    					}
	    					else
	    					{
	    						$("#instance_save").linkbutton("enable");
	    						$("#instance_save .l-btn-text").text("保存");
	    						$.messager.alert('错误',"<p>新增失败！</p>","error");
	    					}
	    				}
						
		    		},
					error: function() {
						$("#instance_save").linkbutton("enable");
						$("#instance_save .l-btn-text").text("保存");
						$.messager.alert('错误','<p>服务异常，新增公司失败，请稍后重试或联系管理员!</p>', 'error');
					}
		    	});
	 		}
 		}
 	}
 	
 	function addCompany(newCompanyInfo) {
 		if(!newCompanyInfo)
 		{
 	 		var orgName = $("#companyName").val();
 	 		var level = '1';
 	 		newCompanyInfo = {orgName:orgName,level:level};
 		}
 		
 		var jsonData = JSON.stringify(newCompanyInfo);
 		$.ajax({
			url: BASE_URL_COMPANY_CRUD  + '?v=' + Math.random(),
			type:'post',
			contentType:"application/json",
			data:jsonData,
			success:function(){
				$.messager.alert("提示","<p>新增成功!</p>","info");
				$('#win').window('close');
				$("#datagrid").datagrid("reload",BASE_URL_COMPANY_SEARCH + '/findByExample' + '?v=' + Math.random());
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
				ddvDatagrid={};
			},
			error:function(){
				$.messager.alert("错误","<p>服务异常，新增公司失败，请重新登录或稍后再试！</p>","error");	
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
			}
		});
 	}
 	
 	function modifyCompany(newCompanyInfo) {
 		var row = $('#datagrid').datagrid('getSelected');
 		if(!newCompanyInfo)
 		{
 	 		var orgName = $("#companyName ").val();
 	 		var level = '1';
 	 		newCompanyInfo = {orgName:orgName,level:level};
 		}
 		
 		var jsonData = JSON.stringify(newCompanyInfo);
 		$.ajax({
			url: BASE_URL_COMPANY_CRUD + '/' + row.id  + '?v=' + Math.random(),
			type:'put',
			contentType:"application/json",
			data:jsonData,
			success:function(){
				$.messager.alert("提示","<p>修改成功!</p>","info");
				$('#win').window('close');
				$("#datagrid").datagrid("reload",BASE_URL_COMPANY_SEARCH + '/findByExample' + '?v=' + Math.random());
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
				ddvDatagrid={};
				$('#comboxCompanyName').combobox({
					editable: false,
					url: BASE_URL_COMPANY_SEARCH + '/findByExample' + '?v=' + Math.random(),
					valueField: 'id',
				    textField: 'orgName',
				    method:'get',
				    loadFilter:function(data){
				    	return data.content;
				    }
				    
				});
			},
			error:function(){
				$.messager.alert("错误","<p>服务异常，修改公司信息失败，请重新登录或稍后再试！</p>","error");	
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
			}
		});
 	}
 	//修改提示
 	function update(){
 		/*$("#win").window('setTitle','公司-修改');*/
 		var row = $('#datagrid').datagrid('getSelected');
 		var ddvRow = null;
 		for(var i in ddvDatagrid)
 		{
 			ddvRow = ddvDatagrid[i].datagrid('getSelected');
 			if(ddvRow)
 			{
 				break;
 			}
 		}
 		if(row == null && ddvRow == null){
 			$.messager.alert('警告',"<p>请选中要修改的记录!</p>","warning");
 		}else{
 			modifyOrAddFlag = false;
 			$('#addForm')[0].reset();
 			if(row)
 			{
 				$("#companyName").val(row.orgName);
 				$("#win").window('setTitle','公司管理-修改');
 				$('#win').window('open');
 			}
 			else
 			{
 				ddvRow = ddvDatagrid[i].datagrid('getSelected');
 				$("#companyName").val(ddvRow.orgName);
 				$("#winEdit").window('setTitle','部门管理-修改');
 				$("#comboxCompanyName").combobox('setValue',ddvRow.orgIdFor);
 				$("#comboxDepartment").val(ddvRow.orgName);
 				$('#winEdit').window('open');
 			}
		}
 	}
	
	//导入
	function import_link()
	{
		$('#import_link').window('open'); 
	}
	
 	//删除
 	function del(){
 		var row = $('#datagrid').datagrid('getSelected');
 		var ddvRow = null;
 		for(var i in ddvDatagrid)
 		{
 			ddvRow = ddvDatagrid[i].datagrid('getSelected');
 			if(ddvRow)
 			{
 				break;
 			}
 		}
 		if(row == null && ddvRow == null){
 			$.messager.alert('警告',"<p>请选中要删除的记录!</p>","warning");
 		}
 		var id = null;
 		if(row!=null){
 			id = row.id;
 			var param = {id:id,level:row.level};
 		}
 		if(ddvRow!=null){
 			id = ddvRow.id;
 			var param = {id:id,level:ddvRow.level};
 		}
 			$.ajax({
				url:BASE_URL_COMPANY + '/company/checkIsCanDelete' + '?v=' + Math.random(),
				dataType:'json',
				type:'get',
				data:param,
				contentType:"application/json",
				success:function(result){
					if(result.isCanDelete){
						$.messager.confirm('温馨提示','<p>你真的要删除么?</p>',function(r){
			 				if (r){
							 		$.ajax({
										url:BASE_URL_COMPANY + '/' + id  + '?v=' + Math.random(),
										dataType:'json',
										type:'delete',
										contentType:"application/json",
										success:function(){
											$.messager.alert('提示','<p>删除成功!</p>','info');
											$("#datagrid").datagrid("reload", BASE_URL_COMPANY_SEARCH + '/findByExample?v=' + Date.parse(new Date()));
											ddvDatagrid={};
										},
										error:function(){
											$.messager.alert("错误","<p>服务异常，删除公司失败，请重新登录或稍后再试！</p>","error");	
										}
							 		});
			 				}
			 			});
					}else{
						//alert("error");
						$.messager.alert('警告','<p>' + result.reason + '</p>','warning');
					}
				},
				error:function(){
					$.messager.alert('错误','<p>数据读取失败!</p>',"error");
				}
	 		});
 	}
 	
 	
 	function onCancleEdit(){
 		$('#win').window('close');
 		$("#datagrid").datagrid("reload", BASE_URL_COMPANY_SEARCH + '/findByExample' + '?v=' + Math.random());
 	}

	function search(){
		
		//dataRetrieval('#txtBeginTime','#txtEndTime');
		$("#datagrid").datagrid("reload", BASE_URL_COMPANY_SEARCH + '/findByExample' + '?v=' + Math.random());
	}
	
	function rePage(){
		$('#win').window('close');
		$("#datagrid").datagrid("reload", BASE_URL_COMPANY_SEARCH + '/findByExample' + '?v=' + Math.random());
	}
	
	
	
	//新增和修改保存
	function onSave2(){
		if($("#addForm2").form("validate")){
			$("#instance_save").linkbutton("disable");
			$("#instance_save .l-btn-text").text("提交中...");
	 		var ddvRow = null;
	 		for(var i in ddvDatagrid)
	 		{
	 			ddvRow = ddvDatagrid[i].datagrid('getSelected');
	 			if(ddvRow)
	 			{
	 				break;
	 			}
	 		}
			var orgName = $("#comboxDepartment").val();
			var parent = $('#comboxCompanyName').combobox('getText');
			var level ='2';
			departmentInfo = {
					orgName:orgName,
					level:'2',
					parent:BASE_URL_COMPANY+'/'+ $('#comboxCompanyName').combobox('getValue')
			};
			var checkParam = {name:orgName,parent:parent,level:level};
			if(!modifyOrAddFlag){
				var row = ddvDatagrid[i].datagrid('getSelected');
				checkParam.originalId = row.id;
	 	 		if(row.orgName == checkParam.name && row.orgNameFor==checkParam.parent) // 未修改领域部门的名字，则可以直接修改
				{
	 	 			modifydepartment(departmentInfo);
				}
				else
				{
					$.ajax({
			    		type: "get",
			    		url: BASE_URL_COMPANY_SEARCH + '/checkIsCanSave' + '?v=' + Math.random(),
			    		data: checkParam,
			    		contentType: "application/json",
			    		success: function(result) {
			    			if(result.isCanSave == true)
		    				{
			    				modifydepartment(departmentInfo);
		    				}
		    				else 
	    					{
		    					if (result.errorCode == "DUPLICATE") 
								{
			    					$("#instance_save").linkbutton("enable");
			    					$("#instance_save .l-btn-text").text("保存");
									$.messager.alert('错误',"<p>修改失败，部门已存在！</p>","error");
								}
								else
								{
									$("#instance_save").linkbutton("enable");
									$("#instance_save .l-btn-text").text("保存");
									$.messager.alert('错误',"<p>修改失败！</p>","error");
								}
	    					}
			    		},
						error: function() {
							$("#instance_save").linkbutton("enable");
							$("#instance_save .l-btn-text").text("保存");
							$.messager.alert('错误','<p>服务异常，修改部门信息失败，请稍后重试或联系管理员!</p>', 'error');
						}
			    	});
				}				
			}else{
				$.ajax({
		    		type: "get",
		    		url: BASE_URL_COMPANY_SEARCH + '/checkIsCanSave' + '?v=' + Math.random(),
		    		data: checkParam,
		    		contentType: "application/json",
		    		success: function(result) {
		    			if(result.isCanSave == true)
	    				{
		    				addDepartment(departmentInfo)
	    				}
	    				else 
    					{
	    					if (result.errorCode == "DUPLICATE") 
							{
		    					$("#instance_save").linkbutton("enable");
		    					$("#instance_save .l-btn-text").text("保存");
								$.messager.alert('错误',"<p>新增失败，部门名称已存在！</p>","error");
							}
							else
							{
								$("#instance_save").linkbutton("enable");
								$("#instance_save .l-btn-text").text("保存");
								$.messager.alert('错误',"<p>新增失败！</p>","error");
							}
    					}
		    		},
					error: function() {
						$("#instance_save").linkbutton("enable");
						$("#instance_save .l-btn-text").text("保存");
						$.messager.alert('错误','<p>服务异常，新增部门信息失败，请稍后重试或联系管理员!</p>', 'error');
					}
		    	});
			}
		}
	}
	
	function addDepartment(departmentInfo) {
		if(!departmentInfo)
		{
			var orgName = $("#comboxDepartment").val();
			var parent = $("#comboxCompany").combobox('getValue');
			departmentInfo = {
					orgName:orgName,
					parent:BASE_URL_COMPANY+'/'+ $('#comboxCompanyName').combobox('getValue'),
					level:'2'
			};
		}
		var jsonStr = JSON.stringify(departmentInfo);
		$.ajax({
			url: BASE_URL_COMPANY + '?v=' + Math.random(),
			type:'post',
			contentType:"application/json",
			data: jsonStr,
			timeout:30000,
			success:function(){
				$.messager.alert('提示',"<p>新增成功!</p>","info");
				$('#winEdit').window('close');
				$("#datagrid").datagrid("reload",BASE_URL_COMPANY_SEARCH + '/findByExample' + '?v=' + Math.random());
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
				ddvDatagrid={};
			},
			error:function(xhr,s,err){
				$.messager.alert("错误","<p>服务异常，新增部门失败，请重新登录或稍后再试！</p>","error");	
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
			}
		});
	}
	
	function modifydepartment(departmentInfo) {
		var ddvRow = null;
 		for(var i in ddvDatagrid)
 		{
 			ddvRow = ddvDatagrid[i].datagrid('getSelected');
 			if(ddvRow)
 			{
 				break;
 			}
 		}
		var row = ddvDatagrid[i].datagrid('getSelected');
		if(!departmentInfo)
		{
			var orgName = $("#comboxDepartment").val();
			var parent = $("#comboxCompany").combobox('getValue');
			departmentInfo = {
					orgName:orgName,
					parent:BASE_URL_COMPANY+'/'+ row.orgIdFor,
					level:'2'
			};
		}
		var jsonStr = JSON.stringify(departmentInfo);
		$.ajax({
			url:BASE_URL_COMPANY_CRUD + '/' + row.id  + '?v=' + Math.random(),
			dataType:'json',
			type:'put',
			contentType:"application/json",
			data: jsonStr,
			success:function(){
				$.messager.alert('提示',"<p>修改成功!</p>","info");
				$('#winEdit').window('close');
				$("#datagrid").datagrid("reload",BASE_URL_COMPANY_SEARCH + '/findByExample' + '?v=' + Math.random());
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
				ddvDatagrid = {};
			},
			error:function(xhr,s,err){
				$.messager.alert("错误","<p>服务异常，修改部门信息失败，请重新登录或稍后再试！</p>","error");	
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
			}
			
			
		});
	}
	function onCancleEdit2(){
		$('#winEdit').window('close');
	}
	
	
	
	
	